import pymongo as mg
from typing import Any, Dict, List
from pydantic import BaseModel
from fastapi import APIRouter, Request
import datetime
from core import setting, mgClient
from uuid import uuid1
from sys import getsizeof
db = mgClient['chat']
collection = db.get_collection('share')
current_timestamp = int(datetime.datetime.now().timestamp()*1000)
collection.insert_one({
    "id": 0,
    "userId": 0,
    "uuid": str(uuid1()),
    "data": "",
    "label": "",
    "client_ip": "",
    "date": current_timestamp
})
router = APIRouter(
    prefix="/share",
    tags=["share"]
)

@router.get("/getDataViaUuid")
async def getDataViaUuid(uuid:str):
    queryResult = collection.find({"uuid":uuid})
    resultList = [{"id":i["id"],"date":i["date"],"data":i["data"],"label":i["label"]} for i in queryResult]
    return resultList[0]

class ShareData(BaseModel):
    label:str
    conversation:List[Any]

@router.post("/insertData")
async def insertData(request: Request, userId:int, data:ShareData):
    client_ip = request.client.host
    current_timestamp = int(datetime.datetime.now().timestamp()*1000)
    
    # 删除创建时间超过24小时的数据
    delete_time_limit = current_timestamp - (24 * 60 * 60 * 1000)  # 24小时之前的时间戳
    collection.delete_many({"client_ip": client_ip, "date": {"$lt": delete_time_limit}})
    
    # 检查client_ip在24小时内的insert次数
    count_time_limit = current_timestamp - (24 * 60 * 60 * 1000)  # 24小时之前的时间戳
    query_count = collection.count_documents({"client_ip": client_ip, "date": {"$gt": count_time_limit}})
    
    data_size = getsizeof(data.conversation)
    print("Data size: ", data_size)
    if query_count >= 3:
        return {"status": False, "error": "分享失败，每24小时的分享次数不能超过3次"}

    id = 0
    if((collection.count_documents({}))):
        query = collection.find().sort("id",-1).limit(1)[0]
        id = query['id'] + 1
        uuid = str(uuid1()) 
    # 检查data的大小
    if data_size > 500:
        return {"status": False, "error": "分享失败，对话数据过大"}
    collection.insert_one({
        "id": id,
        "userId": userId,
        "uuid": uuid,
        "data": data.conversation,
        "label": data.label,
        "client_ip": client_ip,  # 添加客户端IP到数据集
        "date": current_timestamp})  # 添加当前时间戳到数据集

    return {"status": True, "id": id, "uuid": uuid}
@router.delete("/deleteData")
async def deleteData(id:int):
    collection.delete_one({"id":id})
    return {"status":True}
@router.put("/updateData")
async def updateData(id:int,data:ShareData):
    query = collection.find_one({"id":id})
    query['data'] = data.conversation
    query['label'] = data.label
    query['date'] = int(datetime.datetime.now().timestamp()*1000)
    collection.update_one({"id":id},{"$set":query})
    return {"status":True}
@router.get("/download")
async def download(id:int):
    query = collection.find({"id":id}).limit(1)[0]
    return query['data']